import React, { useState, useRef, useEffect } from 'react';
import {   Row,Slider  ,InputNumber  ,Col,Form,message,Switch,Divider,Image,Space,Tooltip} from 'antd';

import styles from './index.less';
import moment from 'moment'
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { queryDeviceAlarm } from '@/services/deviceAlarm';
import { getDeviceHistoryData } from '@/services/device';
import { getAlarmRulesByAttr ,updateOrsave} from '@/services/alarmRules';
import { updateDeviceAlarm } from '@/services/deviceAlarm';
import UpdateForm from '@/pages/alarm/record/components/UpdateForm';
import { Link,useModel,useRequest, Access } from 'umi';
import ECharts from 'echarts-for-react';
import slg from '@/assets/img/img/slg2.png';



/**
 * 更新节点
 * @param fields
 */
 const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在保存');
  try {
    await updateDeviceAlarm(fields);
    hide();
    message.success('保存成功');
    return true;
  } catch (error) {
    hide();
    message.error('保存失败请重试！');
    return false;
  }
};



const AlarmRulesDetails: React.FC = (props: any) => {
  const { params } = props.match;


  let initFormData=params;
  const [form] = Form.useForm();
  const [alarmSourceEnumDict, setAlarmSourceEnumDict] = useState({});
  const [alarmCategoryEnumDict, setAlarmCategoryEnumDict] = useState({});
  const [alarmLevelEnumDict, setAlarmLevelEnumDict] = useState({});
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState({});
  const [useState1, setUseState1] = useState<boolean>();
  const [useState2, setUseState2] = useState<boolean>();
  const [useState3, setUseState3] = useState<boolean>();
  const [useState4, setUseState4] = useState<boolean>();
  const [value1, setValue1] = useState<number>();
  const [value2, setValue2] = useState<number>();
  const [value3, setValue3] = useState<number>();
  const [value4, setValue4] = useState<number>();
  const [alarmRecord, setAlarmRecord] = useState();
  const [attr, setAttr] = useState<API.SysDeviceAttrItem>();
  const actionRef = useRef<ActionType>();
  const { initialState,setInitialState } = useModel('@@initialState');
  const { mySocket,dicts } = initialState || {};

  const second = useRequest(() => {
    return getDeviceHistoryData(params);
  });
  console.log(second)

  useEffect(() => {
    const setSelectData = async () => {
    const detail = await getAlarmRulesByAttr(params);
    setUseState1(detail.useState1);
    setUseState2(detail.useState2);
    setUseState3(detail.useState3);
    setUseState4(detail.useState4);
    setValue1(detail.number1);
    setValue2(detail.number2);
    setValue3(detail.number3);
    setValue4(detail.number4);
    setAttr(detail?.attr);


    };
    setSelectData();
    if(dicts){
      setAlarmSourceEnumDict(dicts["5Enum"]);
      setAlarmCategoryEnumDict(dicts["6Enum"]);
      setAlarmLevelEnumDict(dicts["8Enum"])

    }
  }, []);

  const validatorValue = async (_: any, value: string) => {
    const promise = Promise;
    if(value2!=null&&value!=null){
      if(Number(value)<=value2){
        return promise.reject("值不能小于高报警值");
      }
    }
    return promise.resolve();
  };

  const validatorValue2 = async (_: any, value: string) => {
    const promise = Promise;
    if(value!=null&&value1!=null){
      if(Number(value)>=value1){
        return promise.reject("值不能大于高高报警值");
      }
    }
    if(value!=null&&value3!=null){
      if(Number(value)<=value3){
        return promise.reject("值不能小于低报警值");
      }
    }
    return promise.resolve();
  };

  const validatorValue3 = async (_: any, value: string) => {
    const promise = Promise;
    if(value!=null&&value2!=null){
      if(Number(value)>=value2){
        return promise.reject("值不能大于高报警值");
      }
    }
    if(value!=null&&value4!=null){
      if(Number(value)<=value4){
        return promise.reject("值不能小于低低报警值");
      }
    }
    return promise.resolve();
  };
  const validatorValue4 = async (_: any, value: string) => {
    const promise = Promise;
    if(value3!=null&&value!=null){
      if(Number(value)>=value3){
        return promise.reject("值不能大于低报警值");
      }
    }
    return promise.resolve();
  };

  const changeValue1= async (e,value) => {
    console.log(initFormData)
    let formData={...initFormData};
    formData.alarmType='602';
    formData.maxValue=value;
    formData.useState=e?1:0;
    if(e==false||(e==true &&   formData.maxValue!=null)){
      updateOrsave(formData);
    }
    changeValue2(useState2,value2,value);
  }

  const changeValue2= async (e,value,val1) => {

    let formData={...initFormData};
    formData.alarmType='603';
    formData.maxValue= (val1==null? value1:val1);
    formData.minValue=value;
    formData.useState=e?1:0;
  
    if(e==false||(e==true &&   formData.minValue!=null &&   formData.maxValue!=null)){
      updateOrsave(formData);
    }
   
  }
  const changeValue3= async (e,value,val1) => {
    let formData={...initFormData};
    formData.alarmType='604';
    formData.maxValue=value;
    formData.minValue=  val1==null? value4:val1; ;
    formData.useState=e?1:0;
    
    if(e==false||(e==true &&   formData.minValue!=null &&   formData.maxValue!=null)){
      updateOrsave(formData);
    }
  }

  const changeValue4= async (e,value) => {
    let formData={...initFormData};
    formData.alarmType='605';
    formData.minValue=value;
    formData.useState=e?1:0;
   
    if(e==false||(e==true &&   formData.minValue!=null)){
      updateOrsave(formData);
    }
    changeValue3(useState3,value3,value);
  }

  const columns: ProColumns[] = [
   
    {
      title: '报警时间',
      dataIndex: 'alarmTime',

    },
    {
      title: '报警类别',
      dataIndex: 'alarmType',
      valueEnum: alarmCategoryEnumDict
    },
    {
      title: '报警级别',
      dataIndex: 'alarmLevel',
      valueEnum:  alarmLevelEnumDict,
    },
    {
      title: '报警数值',
      dataIndex: 'alarmValue',
    }, {
      title: '信息来源',
      dataIndex: 'defectSource',
      valueEnum: alarmSourceEnumDict,
    },
    {
      title: '处置建议',
      search: false,
      width: 200,
      dataIndex: 'handleOpinions',
      render: (text, record) => (
        <Space size="middle"  className={styles.textOverflow}>
          <Tooltip placement="topLeft" title={text} arrowPointAtCenter>
           {text}
          </Tooltip>
        </Space>
       ),
    },
    {
      title: '处置状态',
      dataIndex: 'state',
      valueEnum: {0:'未处置',1:'已处置'}
    },
    {
      title: '报警处置信息',
      dataIndex: 'alarmAnswer',
      render: (text, record, _, action) =>{
         if(record.attrId==params.attrId&&alarmRecord==null){
          setAlarmRecord(record);
          initFormData.alarmName=record?.alarmName;
          initFormData.alarmLevel=record?.alarmLevel;
         
         }
        }
      
    },
    {
      title: '操作',
      dataIndex: 'state',
      valueType: 'option',
      render: (text, record, _, action) => (
        <>
       {record.state==0?
        <a onClick={async () => {
            handleUpdateModalVisible(true);
            setFormValues(record);
          }}
        >处置</a>:null} 
        </>
      )
    },
  ];


  
  const option = {
    color: ["red", "green", "yellow"],
    grid: {
      top: 50,
      left: 60,
      right: 50,
      bottom: 30
    },
    title: {
      text: '',
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      // data: [second.data?.series[0].name, second.data?.series[1].name, second.data?.series[2].name],
      textStyle: {
        color: '#ddd',
      },
    },
    toolbox: {
      show: false,
    },
    xAxis: {
    
      type: 'category',
      boundaryGap: false,
      data: second?.data?.phaseTime,
      splitLine: {
        show: false,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    yAxis: {
      type: 'value',
     // min:0,  //取0为最小刻度
      // max: 60, //取100为最大刻度
      axisLabel: {
        formatter: '{value}'
      },
      splitLine: {
        show: true,
        lineStyle: {
          type: 'dashed'
        }
      },
      axisLine: {
        lineStyle: {
          type: 'dashed',
          color: '#ddd',//左边线的颜色
        }
      },
    },
    series:[
      {
        data: second?.data?.data,
        name:alarmRecord?.browseName,
        type: 'line'
      }
    ]
  };

  return (
   <div className={styles.main}>
          {attr !=null?<>  <Row style={{alignItems:'center'}}>   
           <Image    src={slg}  preview={false} />
             <div>
                  <span  className={styles.title} > {alarmRecord?.browseName} </span>
                  <span className={styles.updateTimeText} > (最新同步时间：{ moment().format("YYYY-MM-DD HH:mm:ss")})</span>
                </div>
         </Row>
        <Row gutter={16}> 
         <Col className={styles.dataItem} span={8} >
          <div className={  styles.dividerItem}>
             <span>数值上限</span>
             <Divider orientation="left" style={{  margin: '-15px 0',color:'#ccc'}}    >{attr?.maxValue||100}</Divider>
             </div>
          <Row  > 
            <div style={{width:'30px',marginLeft:'60px'}} >
              {second?.data? <Slider vertical step={0.1}  min={attr?.minValue||0}   max={attr?.maxValue||100} defaultValue={second?.data?.data[second?.data?.data.length-1]} disabled={true} />:null}
            </div>
            <div className={styles.right} style={{flex:1}} >
            <Form
              form={form}
              >
                <Row className={styles.item}>
                  <div className={styles.text} style={{borderBottom: '2px solid red'}}>高高报警</div>
                  <Form.Item  className={styles.input} name={"value1"}  rules={[{validator: validatorValue}]}>
                    <InputNumber  defaultValue={value1}  disabled={useState1==1||useState2==1?false:true} onChange={(e)=>{setValue1(e);changeValue1(useState1,e)}}/>
                  </Form.Item>
                  <Form.Item valuePropName="checked" className={styles.rightswitch}>
                    <Switch  size='small'  defaultChecked={useState1}  onChange={(e)=>{setUseState1(e);changeValue1(e,value1)}}/>
                  </Form.Item>
                </Row>
                <Row className={styles.item}>
                  <div className={styles.text}>高报警</div>
                  <Form.Item  className={styles.input}  name={"value2"}  rules={[{validator: validatorValue2}]}>
                    <InputNumber  defaultValue={value2}  disabled={useState2==1?false:true} onChange={(e)=>{setValue2(e);changeValue2(useState2,e)}} />
                  </Form.Item>
                  <Form.Item valuePropName="checked" className={styles.rightswitch}>
                    <Switch  size='small'    defaultChecked={useState2}   onChange={(e)=>{setUseState2(e);changeValue2(e,value2)}}/>
                  </Form.Item>
                </Row>
                <Row className={styles.item} style={{    marginTop:'80px'}}>
                  <div className={styles.text}>低报警</div>
                  <Form.Item  className={styles.input} name={"value3"}  rules={[{validator: validatorValue3}]}>
                    <InputNumber  defaultValue={value3}  disabled={useState3==1?false:true} onChange={(e)=>{setValue3(e);changeValue3(useState3,e)}} />
                  </Form.Item>
                  <Form.Item valuePropName="checked" className={styles.rightswitch}>
                    <Switch  size='small'   defaultChecked={useState3}  onChange={(e)=>{setUseState3(e);changeValue3(e,value3)}}/>
                  </Form.Item>
                </Row>
                <Row className={styles.item}>
                  <div className={styles.text} style={{borderBottom: '2px solid red'}}>低低报警</div>
                  <Form.Item  className={styles.input} name={"value4"}  rules={[{validator: validatorValue4}]}>
                    <InputNumber  defaultValue={value4}  disabled={useState3==1||useState4==1?false:true}  onChange={(e)=>{setValue4(e);changeValue4(useState4,e)}}/>
                  </Form.Item>
                  <Form.Item valuePropName="checked" className={styles.rightswitch}>
                    <Switch  size='small'  defaultChecked={useState4}   onChange={(e)=>{setUseState4(e);changeValue4(e,value4)}} />
                  </Form.Item>
                </Row>
            </Form>
            </div>
          </Row>
          <div className={  styles.dividerItem}> <Divider orientation="left" style={{color:'#ccc',margin: '-5px 0px -15px'}}    >{attr?.minValue||'0'}</Divider>  数值下限</div>
        </Col>
        <Col  className={styles.dataItem} span={16} style={{padding:0}}>
        <ProTable
          size="small"
          headerTitle="报警"
          className={styles.alarmTable}
          actionRef={actionRef}
          rowKey="id"
          search={false}
          request={(tableParams) => queryDeviceAlarm({ ...tableParams, ...{ deviceId: params.deviceId } })}
          columns={columns}
          options={false}
          pagination={{
            defaultCurrent: 1,
            defaultPageSize: 5,
          }}
        />
        </Col>
        </Row>
        <Row style={{height:'300px',marginTop:'15px'}}>

          <ECharts  style={{height:'300px',width:'100%'}}   option={option} />
        </Row></>:<></>}
      {formValues && Object.keys(formValues).length ? (
        <UpdateForm
          onSubmit={async (value) => {
            const success = await handleUpdate(value);
            if (success) {
              handleUpdateModalVisible(false);
              setFormValues({});
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}
          onCancel={() => {
            handleUpdateModalVisible(false);
            setFormValues({});
          }}
          updateModalVisible={updateModalVisible}
          values={formValues}
      
        />
      ) : null}
    </div>
  
  );
};

export default AlarmRulesDetails;